package com.yicong.ants.ui.video;

import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.model.event.CommonEvent;
import com.cchao.simplelib.ui.activity.BaseTitleBarActivity;
import com.cchao.simplelib.util.CallBacks;
import com.cchao.simplelib.util.StringHelper;
import com.luck.picture.lib.entity.LocalMedia;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.databinding.VideoPublishActivityBinding;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.CopyHelper;
import com.yicong.ants.manager.ImageHelper;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.UiAssistant;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.config.ZzConfigs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.view.dialog.AntLinkDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class VideoPublishActivity extends BaseTitleBarActivity<VideoPublishActivityBinding> implements View.OnClickListener {

    List<LocalMedia> mMediaList = new ArrayList<>();
    int mCompressProgress;
    CallBacks.Int mCompressCallBack;
    private String mCompressorUrl = null;

    @Override
    protected int getLayout() {
        return R.layout.video_publish_activity;
    }

    @Override
    protected void initEventAndData() {
        setTitleText("发布视频");
        mDataBind.setClick(this);
//        initViews();
        updateVideoView();

        addTitleMenuItem(UiAssistant.getAtyMenuText(mContext, "发布"), view -> {
            if (StringHelper.isEmpty(mDataBind.title.getText())) {
                showToast("请写下视频描述");
                return;
            }

            if (mMediaList.size() == 0) {
                showToast("请分享图片或视频");
                return;
            }

            if (mCompressorUrl != null) {
                showProgress("正在发布");
                onPushVideo(mCompressorUrl);
            } else {
                UiHelper.showToast("视频上传失败,请重新上传");
            }
        });

        CopyHelper.listenClip();
    }

    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (event.getCode()) {
            case Constants.Event.Ant_Link_Copy:
                String antUrl = CopyHelper.extractClipAnts();
                if (StringHelper.isEmpty(antUrl)) {
                    return;
                }

                mDataBind.link.setText(antUrl);
                break;

        }
    }

    private void updateVideoView() {
        if (mMediaList.size() == 0) {
            UiHelper.setVisibleElseGone(mDataBind.play, false);
            UiHelper.setVisibleElseGone(mDataBind.delete, false);
            mDataBind.image.setScaleType(ImageView.ScaleType.CENTER);
            mDataBind.image.setImageResource(R.drawable.journal_add_image);
            mDataBind.image.setBackgroundColor(UiHelper.getColor(R.color.eee_color));
            return;
        }

        UiHelper.setVisibleElseGone(mDataBind.play, true);
        UiHelper.setVisibleElseGone(mDataBind.delete, true);
        mDataBind.image.setBackgroundColor(UiHelper.getColor(R.color.black));
        String imagePath = mMediaList.get(0).getRealPath();
        if (StringHelper.isEmpty(imagePath)) {
            imagePath = mMediaList.get(0).getParentFolderName();
        }

        Glide.with(mContext)
                .load(imagePath)
                .into(mDataBind.image);

        mCompressCallBack = Dialogs.showShortVideoUpload(thisActivity);
        BusinessHelper.compressVideo2(imagePath, intValue -> {
            mCompressCallBack.onCallBack(intValue);
            if (intValue == 200) {
                onSaveVideo();
            }
        });
    }

    void onSaveVideo() {
        showProgress();
        File file = new File(ImageHelper.mCompressOutputPath);
        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
        MultipartBody.Part videoFile = MultipartBody.Part.createFormData("file", file.getName(), requestFile);

        addSubscribe(RetrofitHelper.getApis().saveVideo(videoFile)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        return;
                    }
                    mCompressorUrl = respBean.getData().getUrl();
                }, RxHelper.getHideProgressConsumer(this)));
    }

    /**
     * 上传视频
     *
     * @param videoUrl
     */
    private void onPushVideo(String videoUrl) {
        Map<String, String> map = new HashMap<>();
        map.put("title", mDataBind.title.getText().toString().trim());
        map.put("video", videoUrl);
        if (StringHelper.isNotEmpty(mDataBind.link.getText())) {
            if (!RouterHelper.isAntsLink(mDataBind.link.getText().toString())) {
                showToast("请填写蚁丛链接");
                return;
            }
            map.put("foreign_link", mDataBind.link.getText().toString());
        }

        addSubscribe(RetrofitHelper.getApis().pushVideo(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    hideProgress();
                    showToast(respBean.getMsg());
                    if (respBean.isCodeSuc()) {
                        finish();
                    }
                }, RxHelper.getHideProgressConsumer(this)));
    }


    @Override
    protected void onLoadData() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                onBackPressed();
                break;

            case R.id.image:
                if (mMediaList.size() == 0) {
                    ImageHelper.addShortVideo(thisActivity, localMediaList -> {
                        mMediaList = localMediaList;
                        updateVideoView();
                    });
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    String type = "video/mp4";
                    intent.setDataAndType(Uri.fromFile(new File(mMediaList.get(0).getRealPath())), type);
                    startActivity(intent);
                }
                break;

            case R.id.play:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                String type = "video/mp4";
                intent.setDataAndType(Uri.fromFile(new File(mMediaList.get(0).getRealPath())), type);
                startActivity(intent);
                break;
            case R.id.ant_link:
                AntLinkDialog.newInstance(this).show(getSupportFragmentManager());
                break;
            case R.id.link_preview:
                if (StringHelper.isEmpty(mDataBind.link.getText())) {
                    showToast("请先填写链接地址");
                    return;
                }
                if (!RouterHelper.isAntsLink(mDataBind.link.getText().toString())) {
                    showToast("请填写蚁丛链接");
                    return;
                }
                RouterHelper.tryRoutePlatformUri(thisActivity, mDataBind.link.getText().toString());
                break;
            case R.id.question:
                //跳转web页，后续会给出url地址
                ZzConfigs.toWebActivityByUrlNotLogin(this,"project_ant_link");
                break;

            case R.id.delete:
                mMediaList.clear();
                updateVideoView();
                break;
            case R.id.ant_link_show:
                UiHelper.setVisibleElseGone(mDataBind.antLinkContainer, !UiHelper.isVisible(mDataBind.antLinkContainer));

                mDataBind.linkSign.setImageResource(R.drawable.common_up_sign);
                if (UiHelper.isVisible(mDataBind.antLinkContainer)) {
                    mDataBind.linkSign.setImageResource(R.drawable.common_down_sign);
                }
                break;

        }
    }
}